﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using monitor_2_DBwork;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace monitor_server_2_WPF
{
    /// <summary>
    /// Логика взаимодействия для TrustedAddressListTabControl.xaml
    /// </summary>
    public partial class TrustedAddressListTabControl : Res.IControlForMainWindow
    {
        //private bool _visible;
        private readonly ObservableCollection<Regions> _regionsList;
        private readonly Dictionary<string, ObservableCollection<TrustedAddresses>> _addressList;
        private Dictionary<string, List<string>> _regionAddressList;
        private const ListSortDirection Sort = ListSortDirection.Ascending;
        private bool? _addAddress = true;

        class Regions
        {
            public string Region { get; set; }
        }

        class TrustedAddresses
        {
            public string Address { get; set; }
        }

        public TrustedAddressListTabControl()
        {
            InitializeComponent();

            ControlsPanel.Background = new SolidColorBrush(Res.LighBlack);

            Item1.Header = Res.Rm.GetString("TrustedAddressesList");

            RegionLabel.Content = Res.Rm.GetString("Region");
            IpLabel.Content = Res.Rm.GetString("IPAddress");

            IpBox.TextChanged += IpBox_TextChanged;

            ChangeAcceptButton(true, false);

            var gc1 = new DataGridTextColumn
                {
                    Header = Res.Rm.GetString("Region"),
                    Binding = new Binding("Region")
                };
            DataGobl.Columns.Add(gc1);
            DataGobl.BorderThickness = new Thickness(1,1,0,1);
            DataGobl.AutoGenerateColumns = false;
            _regionsList = new ObservableCollection<Regions>();
            DataGobl.ItemsSource = _regionsList;
            DataGobl.CanUserAddRows = false;
            DataGobl.CanUserDeleteRows = false;
            DataGobl.IsReadOnly = true;

            var gc2 = new DataGridTextColumn()
            {
                Header = Res.Rm.GetString("IPAddress"),
                Binding = new Binding("Address")
            };
            DataGip.BorderThickness = new Thickness(0,1,1,1);
            DataGip.AutoGenerateColumns = false;
            DataGip.Columns.Add(gc2);

            DataGip.CanUserAddRows = false;
            DataGip.CanUserDeleteRows = false;
            DataGip.IsReadOnly = true;

            _addressList = new Dictionary<string, ObservableCollection<TrustedAddresses>>();

            DataGobl.SelectedCellsChanged += DataG_SelectedCellsChanged;
            DataGip.SelectedCellsChanged += DataGip_SelectedCellsChanged;
        }

        void IpBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var t = (sender as TextBox).Text;
            if (t.Trim() == "")
            {
                ChangeAcceptButton(true,false);
                return;
            }
            IPAddress ip;
            const string mask = "[0-9]{0,3}\\.[0-9]{0,3}\\.[0-9]{0,3}\\.[0-9]{0,3}";
            
            if (!IPAddress.TryParse(t, out ip) || !Regex.IsMatch(t, mask))
            {
                ChangeAcceptButton(true, false);
                return;
            }
            var chk = DBwork.CheckTrustedAddress(t);
            ChangeAcceptButton(chk == "notExist", true);
        }

        void DataGip_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            var dg = sender as DataGrid;
            if (dg == null)
                return;
            if (dg.SelectedCells.Count < 1)
                return;
            var item = dg.SelectedCells[0];
            var address = item.Item as TrustedAddresses;
            if (address != null)
            {
                var name = address.Address;
                IpBox.Text = name;
            }
        }

        void DataG_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            IpBox.Text = string.Empty;
            var dg = sender as DataGrid;
            if (dg == null)
                return;
            if (dg.SelectedCells.Count < 1)
                return;
            var item = dg.SelectedCells[0];
            var regions = item.Item as Regions;
            if (regions != null)
            {
                var name = regions.Region;
                DataGip.ItemsSource = _addressList[name];
                DataGip.Tag = name;
                RegionBox.Text = name;
            }
            
        }

        public UIElement GetControl(out MainWindow.HidingDelegate del)
        {
            del = null;
            //del = () =>
            //{
            //    _visible = false;
            //};
            //_visible = true;
            Update();
            return this;
        }

        private void ChangeAcceptButton(bool add, bool enabled)
        {
            if (enabled == false)
            {
                AcceptButton.Content = Res.Rm.GetString("InputAddress");
                AcceptButton.IsEnabled = false;
                _addAddress = null;
                return;
            }
            AcceptButton.IsEnabled = true;
            var dp = new DockPanel();
            var im = new Image {Stretch = Stretch.None, Margin = new Thickness(0,0,5,0)};
            var tb = new TextBlock();
            if (add)
            {
                if (_addAddress == true)
                    return;
                _addAddress = true;
                tb.Text = Res.Rm.GetString("Add");
                im.Source = Res.GetBitMapFromPng("accept_image_16");
            }
            else
            {
                if (_addAddress == false)
                    return;
                _addAddress = false;
                tb.Text = Res.Rm.GetString("Delete");
                im.Source = Res.GetBitMapFromPng("delete_image_16");
            }
            
            dp.Children.Add(im);
            dp.Children.Add(tb);

            AcceptButton.Content = dp;
        }

        private void Update()
        {
            try
            {
                _regionAddressList = DBwork.GetTrustedAddresses();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Res.Rm.GetString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (_regionAddressList.ContainsKey("err:"))
            {
                MessageBox.Show(_regionAddressList["err:"][0], Res.Rm.GetString("Error"), MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            _regionsList.Clear();
            _addressList.Clear();
            foreach (var obl in _regionAddressList)
            {
                _regionsList.Add(new Regions{Region=obl.Key});
                var ta = new ObservableCollection<TrustedAddresses>();
                foreach (var ip in obl.Value)
                {
                    ta.Add(new TrustedAddresses {Address = ip});
                }
                if(!_addressList.ContainsKey(obl.Key))
                    _addressList.Add(obl.Key, ta);
            }
            DataGobl.Items.SortDescriptions.Clear();
            DataGobl.Items.SortDescriptions.Add(new SortDescription("Region", Sort));
            DataGobl.Columns[0].SortDirection = Sort;

            if (DataGip.Tag != null && (DataGip.Tag as string) !=null)
                DataGip.ItemsSource = _addressList[DataGip.Tag as string];

            //DataGip.ItemsSource = _addressList[];

        }

        private void SaveAddress()
        {
            DBwork.AddTrustedAddress(IpBox.Text, RegionBox.Text);
        }

        private void DeleteAddress()
        {
            DBwork.DeleteData("trustedAddress", IpBox.Text);
        }

        private void Item1_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if ((e.MouseDevice.DirectlyOver as TextBlock) == null ||
                (e.MouseDevice.DirectlyOver as TextBlock).Text != Res.Rm.GetString("TrustedAddressesList"))
                return;
            Update();
        }

        private void AcceptButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (_addAddress == true)
            {
                SaveAddress();
                ChangeAcceptButton(false, true);
            }
            else if (_addAddress == false)
            {
                DeleteAddress();
                ChangeAcceptButton(true, false);
            }
            Update();
        }
    }
}
